package com.shxy.service.impl;

import com.shxy.service.IFileService;
import com.shxy.util.FileNameUtil;
import com.shxy.util.FtpProperties;
import com.shxy.util.FtpUtil;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Log
public class FileService implements IFileService {
    @Autowired
    private FtpProperties ftpProperties;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd");

    @Override
    public String fileUpload(MultipartFile file, String userId) throws IOException {
        // 1、生成文件名
        String fileName = String.format("%s_%s", FileNameUtil.getFileName(userId), file.getOriginalFilename());
        log.info(fileName);
        // 2、生成文件路径
        String filePath = simpleDateFormat.format(new Date());
        // 3、保存上传的文件
        Boolean result = FtpUtil.uploadFile(ftpProperties.getHost(),
                Integer.valueOf(ftpProperties.getPort()), ftpProperties.getUsername(),
                ftpProperties.getPassword(), ftpProperties.getBasePath(),
                filePath, fileName, file.getInputStream());

        // 4、返回地址
        return String.format("%s/%s/%s", ftpProperties.getHttpPath(), filePath, fileName);
    }
}
